package net.starwifi.duobao.web;

import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.mvc.BaseController;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.oauth.Principal;
import net.starwifi.duobao.service.CaptchaService;
import net.starwifi.duobao.service.MemberService;
import net.starwifi.duobao.service.RSAService;
import net.starwifi.duobao.service.SettingService;
import net.starwifi.duobao.utils.IpUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by Administrator on 2015/11/9.
 */
@Controller("loginController")
public class LoginController extends BaseController {

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private RSAService rsaService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private SettingService settingService;

    /**
     * 登录页面
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String index(String redirectUrl, HttpServletRequest request, ModelMap model) {
        model.addAttribute("redirectUrl", redirectUrl);
        model.addAttribute("captchaId", UUID.randomUUID().toString());
        return "/login";
    }

    /**
     * 登录提交
     */
    @RequestMapping(value = "/loginSubmit", method = RequestMethod.POST)
    public @ResponseBody
    Message submit(String captchaId, String captcha, String username, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String password = rsaService.decryptParameter("enPassword", request);
        rsaService.removePrivateKey(request);
        if (!captchaService.isValid(null, captchaId, captcha)) {
            return Message.error("验证码错误");
        }
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return Message.error("用户名密码不能为空");
        }
        if (!captchaService.isValid("adminLogin", captchaId, captcha)) {
            return Message.error("验证码错误");
        }
        Member member=memberService.findByUsernameOrMobile(username);
        if (member == null) {
            return Message.error("用户名或者密码错误");
        }
        if(!member.getIsEnabled()){
            return Message.error("账户失效,请联系商务");
        }
        String lockTime= settingService.findByCode("loginFailureLockTime").getConfigValue();
        int loginFailureLockTime =Integer.parseInt(lockTime);
        if(member.getIsLocked()){
            Date lockedDate = member.getLockedDate();
            Date unlockDate = DateUtils.addMinutes(lockedDate, loginFailureLockTime);
            if (new Date().after(unlockDate)) {
                member.setLoginFailureCount(0);
                member.setIsLocked(false);
                member.setLockedDate(null);
                memberService.update(member);
            } else {
                return Message.error("账户被锁定");
            }
        }
        if (!DigestUtils.md5Hex(password + member.getSalt()).equals(member.getPassword())) {
            String settingFailureCount= settingService.findByCode("loginFailureCount").getConfigValue();
            int settingFailureCountInteger =Integer.parseInt(settingFailureCount);
            int loginFailureCount = member.getLoginFailureCount() + 1;
            if (loginFailureCount >= settingFailureCountInteger) {
                member.setIsLocked(true);
                member.setLockedDate(new Date());
            }
            member.setLoginFailureCount(loginFailureCount);
            memberService.update(member);
            return Message.error("密码错误,错误:"+settingFailureCount+"次账户将被锁定"+(loginFailureLockTime/60)+"分钟!");
        }
        member.setLoginFailureCount(0);
        member.setLoginIp(IpUtils.getIpAddr(request));
        member.setLoginDate(new Date());
        memberService.update(member);
        Map<String, Object> attributes = new HashMap<String, Object>();
        Enumeration<?> keys = session.getAttributeNames();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            attributes.put(key, session.getAttribute(key));
        }
        session.invalidate();
        session = request.getSession();
        for (Map.Entry<String, Object> entry : attributes.entrySet()) {
            session.setAttribute(entry.getKey(), entry.getValue());
        }
        session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), username));
        return SUCCESS_MESSAGE;
    }

    /**
     * 注销
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String execute(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        session.removeAttribute(Principal.PRINCIPAL_ATTRIBUTE_NAME);
        return "redirect:/";
    }


}
